package com.bit.forum.services.impl;

import com.bit.forum.common.AppResult;
import com.bit.forum.common.ResultCode;
import com.bit.forum.dao.UserMapper;
import com.bit.forum.exception.ApplicationException;
import com.bit.forum.model.Board;
import com.bit.forum.model.User;
import com.bit.forum.services.IUserService;
import com.bit.forum.utils.MD5Utils;
import com.bit.forum.utils.StringUtils;
import com.bit.forum.utils.UUIDUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public void createNormal(User user) {
        //1.非空校验
        if (user == null || StringUtils.isEmpty(user.getUsername())
        || StringUtils.isEmpty(user.getNickname())
                || StringUtils.isEmpty(user.getPassword())
                || StringUtils.isEmpty(user.getSalt())){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常,统一抛出自定义异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //2.按用户名查询用户信息
        User user1 = userMapper.selectByUserName(user.getUsername());
        //2.1 判断用户是否存在
        if (user1 != null){
            //打印日志
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }

        //3.新增用户,设置默认值
        user.setGender((byte)2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        //当前日期
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        //写入数据库
        int row = userMapper.insertSelective(user);
        if (row != 1){
            log.info(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        //打印日志
        log.info("新增用户成功,username= "+user.getUsername());

    }

    @Override
    public User selectByUserName(String username) {
        //非空校验
        if (StringUtils.isEmpty(username)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        //1.非空校验
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.按照用户名查用户信息
        User user = selectByUserName(username);
        //3.对查询结果做非空校验
        if (user == null){
            log.warn(ResultCode.FAILED_LOGIN.toString() + ",username ="+username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //4.对密码校验
        String s = MD5Utils.md5Salt(password, user.getSalt());
        //5.用密文和数据库中存的比较
        if (!s.equalsIgnoreCase(user.getPassword())){
            log.warn(ResultCode.FAILED_LOGIN.toString() + ",密码错误,username ="+username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        return user;
    }

    @Override
    public User selectById(Long id) {
        //1.非空校验
        if (id == null){
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取对象
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if (id == null || id <= 0){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));

        }
        User user = userMapper.selectByPrimaryKey(id);   //查询用户信息

        if (user == null){
            log.warn(ResultCode.ERROR_IS_NUL.toString() + ",board id = "+ id );
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NUL));
        }
        //更新用户的发帖数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() +1);
        //更新数据
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1){
            log.warn(ResultCode.FAILED.toString() + ",受影响的行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        if (id == null || id <= 0){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));

        }
        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);

        if (user == null){
            log.warn(ResultCode.ERROR_IS_NUL.toString() + ",user id = "+ id );
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NUL));
        }
        //更新用户的发帖数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() -1);
        //判断发帖数是否小于0
        if (updateUser.getArticleCount() < 0){
            updateUser.setArticleCount(0);
        }
        //更新数据
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1){
            log.warn(ResultCode.FAILED.toString() + ",受影响的行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

    }

    @Override
    public void modifyInfo(User user) {
        //非空校验
        if (user == null || user.getId() == null || user.getId() <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查user
        User existUser = userMapper.selectByPrimaryKey(user.getId());
        if (existUser == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //定义一个标志位
        boolean checkAttr = false;//false表示验证不通过
        //为true时,其中有一个肯定不为空

        //定义一个专门用来更新的对象,防止用户传入的User对象设置了其它的属性
        //当使用sql进行更新时,覆盖了没有经过校验的字段
        User updateUser = new User();
        //设置用户ID
        updateUser.setId(user.getId());

        //对每一个参数进行校验,并赋值
        //用户名
        if (!StringUtils.isEmpty(user.getUsername()) //用户名不为空
                && !existUser.getUsername().equals(user.getUsername())){  //用户名和以前的一样
            //需要更新用户名(登录名)时,进行唯一性校验
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if (checkUser != null){
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            //可以修改
            updateUser.setUsername(user.getUsername());
            //更新标志位
            checkAttr = true;
        }

        //校验昵称
        if (!StringUtils.isEmpty(user.getNickname()) //用户名不为空
                && !existUser.getNickname().equals(user.getNickname())){  //用户名和以前的一样
            updateUser.setNickname(user.getNickname());
            //更新标志位
            checkAttr = true;
        }

        //性别
        if (user.getGender()!=null //用户名不为空
                && existUser.getGender()!=user.getGender()){  //用户名和以前的一样
            updateUser.setGender(user.getGender());
            if (updateUser.getGender() > 2 || updateUser.getGender() <0){
                updateUser.setGender((byte) 2);
            }
            //更新标志位
            checkAttr = true;
        }

        //邮箱
        if (!StringUtils.isEmpty(user.getEmail()) //用户名不为空
                && !user.getEmail().equals(existUser.getEmail())){  //用户名和以前的一样
            updateUser.setEmail(user.getEmail());
            //更新标志位
            checkAttr = true;
        }

        //电话
        if (!StringUtils.isEmpty(user.getPhoneNum())//用户名不为空
                && !user.getPhoneNum().equals(existUser.getPhoneNum())){  //用户名和以前的一样
            updateUser.setPhoneNum(user.getPhoneNum());
            //更新标志位
            checkAttr = true;
        }

        //个人简历
        if (!StringUtils.isEmpty(user.getRemark())//用户名不为空
                && !user.getRemark().equals(existUser.getRemark())){  //用户名和以前的一样
            updateUser.setRemark(user.getRemark());
            //更新标志位
            checkAttr = true;
        }
        //判断标志位是否执行
        if (checkAttr == false){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //更新
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1){
            log.warn(ResultCode.FAILED.toString() + ",受影响的行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        //非空校验
        if (id == null || id <=0 ||StringUtils.isEmpty(newPassword) || StringUtils.isEmpty(oldPassword)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null || user.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //校验密码是否正确
        //对老密码进行加密,获取密文
        String oldEncryptPassword = MD5Utils.md5Salt(oldPassword, user.getSalt());
        //与用户当前的密码进行比较
        if (!oldEncryptPassword.equalsIgnoreCase(user.getPassword())){
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        //生成新的盐
        String salt = UUIDUtils.UUID_32();
        //生成新密码的密文
        String encryptPassword = MD5Utils.md5Salt(newPassword,salt);
        //构造要更新的对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setSalt(salt);
        updateUser.setPassword(encryptPassword);//新密码对应的密文
        Date date = new Date();
        updateUser.setUpdateTime(date);
        //dao
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1){
            log.warn(ResultCode.FAILED.toString() + ",受影响的行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

    }
}
